package com.qire.manhua.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.qire.antsbinder.dal.exception.DataAccessException;
import com.qire.antscore.annotation.DalExceptionObserve;
import com.qire.antscore.annotation.RouteMapping;
import com.qire.antsrouter.inject.Autowired;
import com.qire.common.constant.CustomEvent;
import com.qire.common.constant.Navigation;
import com.qire.common.constant.Url;
import com.qire.common.support.base.BaseFragment;
import com.qire.common.inject.EventControllerInjector;
import com.qire.common.utils.NoticeEventBus;
import com.qire.common.utils.NoticeEventBus.EventSubscriber;
import com.qire.common.utils.ObserveBinderHelper;
import com.qire.manhua.R;
import com.qire.manhua.controller.UserCenterController;
import com.qire.manhua.dal.service.MessageSetupService;
import com.qire.manhua.databinding.FragmentUserBinding;
import com.qire.manhua.model.viewModel.impl.UserCenterViewModel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

@RouteMapping(path = Navigation.Fragment.UserFragment)
public class UserCenterFragment extends BaseFragment<FragmentUserBinding> {

    @Autowired
    UserCenterViewModel viewModel;

    @Autowired(injector = EventControllerInjector.class)
    UserCenterController controller;

    @Override
    public int layoutRid() {
        return R.layout.fragment_user;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        registerObserver();
        FragmentUserBinding viewDataBinder = viewDataBinder(inflater, container);

        viewDataBinder.setUserCenterViewModel(viewModel);

        controller.onAddition(viewModel);

        // 由于后面消息中心与消息设置都需要用到消息状态，故在当前页面同步一次，理论上应该放在APP初始化时，必经方法里.
        new MessageSetupService().syncPushStateInfoByService();

        return viewDataBinder.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        viewModel.refreshUserDetailData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unregisterObserver();
    }

    protected void registerObserver() {
        ObserveBinderHelper.callRegisterOfDalExceptionObserveBinder(this);
        NoticeEventBus.NOTICE.subscribeEvent(CustomEvent.LOGIN_SUCCESS, loginSuccessHandle);
    }

    protected void unregisterObserver() {
        ObserveBinderHelper.callUnregisterOfDalExceptionObserveBinder(this);
        NoticeEventBus.NOTICE.unSubscribeEvent(loginSuccessHandle);
    }

    @DalExceptionObserve(tags = Url.myIndex)
    public void refreshUserDetailDataExceptionHandle(DataAccessException e) {
        viewModel.refreshUI();
    }

    private EventSubscriber loginSuccessHandle = noticeEvent -> {
        viewModel.refreshUserDetailData();
        return false;
    };
}
